/*
 * @Author: Qimu
 * @Date: 2020-04-19 05:46:51
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-12-13 16:25:00
 * @Description: file content
 * @FilePath: \vue-admin-koa2\koa2_api\module\middleware\checkToken.js
 */
const tools = require('../utlis/tools')
const config = require('../config')
const jwt = require('jsonwebtoken') // 签发Token
const secret = config.jwt_config.secretKey

const checkToken = {
  admin: () => {
    return async (ctx, next) => {
      console.log('经过token校验');
      // console.log('开始解析authorization：', ctx.request);
      let token = ctx.request.header.authorization;
      // console.log('checkToken:', token);
      let decode = jwt.decode(token.split(' ')[1], secret) // 解析jwt payload数据
      // console.log('decode', decode);
      let currentTime = (new Date()).getTime() / 1000 // 获取当前时间戳(秒s)
      if (token) {
        if (currentTime <= decode.exp) {
          ctx.body = {
            'meta': {
              'status': 200,
              'message': 'Token解析成功!'
            }
          }
          await next();
        } else {
          ctx.body = {
            'data': {
              'token': token,
            },
            'meta': {
              'status': 401,
              'message': 'Token过期!'
            }
          };
        }
      } else {  // 没有token
        ctx.body = {
          'meta': {
            'status': 500,
            'message': '没有Token!'
          }
        }
      }
    }
  }
}

module.exports = checkToken
